package com.xxx.video.dynamic.activitys;

import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.ConcatAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.AppBarLayout;
import com.xxx.player.gsyvideoplayer.GSYVideoManager;
import com.xxx.player.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.xxx.player.gsyvideoplayer.listener.BaseVideoAllCallBackImp;
import com.xxx.player.gsyvideoplayer.utils.OrientationUtils;
import com.xxx.player.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.xxx.video.R;
import com.xxx.video.commen.activitys.BaseActivity;
import com.xxx.video.commen.configs.Constant;
import com.xxx.video.commen.configs.UserManager;
import com.xxx.video.commen.utils.AppBarLayoutStateChangeListener;
import com.xxx.video.commen.utils.ResourcesUtils;
import com.xxx.video.commen.utils.SPUtil;
import com.xxx.video.commen.utils.StringUtils;
import com.xxx.video.commen.utils.TimeUtils;
import com.xxx.video.commen.utils.ToastUtils;
import com.xxx.video.dynamic.adapters.DynamicUserInfoAdapter;
import com.xxx.video.dynamic.beans.DynamicConfigBean;
import com.xxx.video.dynamic.presenters.DynamicDetailsPresenter;
import com.xxx.video.dynamic.presenters.IDynamicDetailsView;
import com.xxx.video.login.activitys.LoginActivity;
import com.xxx.video.main.adapters.DynamicDetailsCommentAdapter;
import com.xxx.video.main.beans.DynamicInfoBean;
import com.xxx.video.main.beans.VideoDetailsBean;
import com.xxx.video.mine.activitys.FavoritesActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class DynamicDetailsActivity extends BaseActivity<DynamicDetailsPresenter> implements IDynamicDetailsView {
    @BindView(R.id.pv_dynamic_details)
    StandardGSYVideoPlayer pvDynamicDetails;
    @BindView(R.id.cl_dynamic_details_toolbar)
    ConstraintLayout clDynamicDetailsToolbar;
    @BindView(R.id.abl_dynamic_details)
    AppBarLayout ablDynamicDetails;
    @BindView(R.id.et_dynamic_details_bottom_comment)
    EditText etDynamicDetailsBottomComment;
    @BindView(R.id.rcv_dynamic_details)
    RecyclerView rcvDynamicDetails;

    protected OrientationUtils orientationUtils;
    protected boolean isPlay;

    protected boolean isPause;
    @BindView(R.id.cl_dynamic_details_bottom_comment)
    ConstraintLayout clDynamicDetailsBottomComment;
    private boolean isShowComment = true;
    /**
     * dynamic Id
     */
    private String mDynamicId;
    private ConcatAdapter mConcatAdapter;
    private DynamicUserInfoAdapter mDynamicUserInfoAdapter;
    private DynamicDetailsCommentAdapter mDynamicDetailsCommentAdapter;
    /**
     * start play time
     */
    private long startTime;
    /**
     * is set 4g
     */
    private boolean mIsSet4G;
    @Override
    protected DynamicDetailsPresenter createPresenter() {
        return new DynamicDetailsPresenter(this, this);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_dynamic_details;
    }

    @Override
    public void initData(Bundle extras) {
        if (extras != null) {
            mDynamicId = extras.getString("Id");
        }
        mIsSet4G = SPUtil.getBoolean(Constant.isSet4G, false);

        initList();
        if (UserManager.getInstance().isLogin()) {
            getPresenter().browse(mDynamicId);
        }
        getPresenter().getDynamicReview();
    }

    @Override
    public void showRootLayoutStatus(int status) {
        showLayoutStatus(status);
    }

    @OnClick({R.id.iv_dynamic_details_actionbar_left_icon, R.id.back, R.id.tv_dynamic_details_bottom_comment_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
            case R.id.iv_dynamic_details_actionbar_left_icon:
                onBackPressed();
                break;
            case R.id.tv_dynamic_details_bottom_comment_send:
                if (!UserManager.getInstance().isLogin()) {
                    startLoginActivity();
                    return;
                }
                getPresenter().interaction(mDynamicId);
                break;
            default:
                break;
        }
    }

    /**
     * @param fTitle title
     */
    public void initVideo(String fTitle, String url) {
        orientationUtils = new OrientationUtils(this, getGSYVideoPlayer(), null);
        orientationUtils.setEnable(false);
        if (getGSYVideoPlayer().getFullscreenButton() != null) {
            getGSYVideoPlayer().getFullscreenButton().setOnClickListener(v -> showFull());
        }
        getGSYVideoOptionBuilder(fTitle, url).setVideoAllCallBack(new BaseVideoAllCallBackImp() {
            @Override
            public void onPrepared(String url, Object... objects) {

                if (orientationUtils == null) {
                    throw new NullPointerException("initVideo() or initVideoBuilderMode() first");
                }
                orientationUtils.setEnable(true);
                isPlay = true;
                startTime = System.currentTimeMillis();
                /*
                 * play
                 */
                if (UserManager.getInstance().isLogin()) {
                    getPresenter().play(mDynamicId, 0);
                }
            }


            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                if (orientationUtils != null) {
                    orientationUtils.backToProtVideo();
                }
            }
        })
                .build(getGSYVideoPlayer());
    }

    public void showFull() {
        if (orientationUtils.getIsLand() != 1) {
            orientationUtils.resolveByClick();
        }
        getGSYVideoPlayer().startWindowFullscreen(this, true, true);

    }

    public StandardGSYVideoPlayer getGSYVideoPlayer() {
        return pvDynamicDetails;
    }

    public GSYVideoOptionBuilder getGSYVideoOptionBuilder(String title, String url) {
        ImageView imageView = new ImageView(this);
        return new GSYVideoOptionBuilder()
                .setThumbImageView(imageView)
                .setUrl(url)
                .setCacheWithPlay(true)
                .setVideoTitle(title)
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setNeedShowWifiTip(!mIsSet4G)
                .setSeekRatio(1);
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onPause() {
        super.onPause();
        getGSYVideoPlayer().getCurrentPlayer().onVideoPause();
        if (orientationUtils != null) {
            orientationUtils.setIsPause(true);
        }
        isPause = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getGSYVideoPlayer().getCurrentPlayer().onVideoResume();
        if (orientationUtils != null) {
            orientationUtils.setIsPause(false);
        }
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isPlay) {
            try {
                getPresenter().play(mDynamicId, startTime);
                getGSYVideoPlayer().getCurrentPlayer().release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isPlay && !isPause) {
            getGSYVideoPlayer().onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }

    @Override
    public void initList() {
        ablDynamicDetails.addOnOffsetChangedListener(new AppBarLayoutStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    clDynamicDetailsToolbar.setVisibility(View.GONE);
                } else if (state == State.COLLAPSED) {
                    clDynamicDetailsToolbar.setVisibility(View.VISIBLE);
                } else {
                    clDynamicDetailsToolbar.setVisibility(View.GONE);
                }
            }
        });
        rcvDynamicDetails.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    public void initDynamicInfoData2View(List<DynamicInfoBean.InteractionListBean> interactionList) {
        if (!isShowComment) {
            return;
        }
        /*
         * dynamic list
         */
        mDynamicDetailsCommentAdapter = new DynamicDetailsCommentAdapter(this);
        mConcatAdapter.addAdapter(mDynamicDetailsCommentAdapter);
        mDynamicDetailsCommentAdapter.setData(interactionList);
    }

    @Override
    public void startChatActivity(DynamicInfoBean.DynamicBean dynamicBean) {
        Bundle bundle = new Bundle();
        bundle.putString("Id", dynamicBean.fUserId);
        bundle.putString("userName", dynamicBean.fUserName);
        bundle.putString("userAvatar", dynamicBean.fPicurl);
        intent2Activity(ChatActivity.class, bundle);
    }

    @Override
    public void addFriendSuccess() {
        if (mDynamicUserInfoAdapter != null) {
            mDynamicUserInfoAdapter.addFriendSuccess();
        }
    }

    @Override
    public void addCommentSuccess() {
        hideKeyBoard();
        if (mDynamicDetailsCommentAdapter != null) {
            DynamicInfoBean.InteractionListBean interactionListBean = new DynamicInfoBean.InteractionListBean();
            interactionListBean.fCommtenterPicurl = UserManager.getInstance().getUserAvatar();
            interactionListBean.fCommtenterName = UserManager.getInstance().getUserName();
            interactionListBean.fCreateTime = TimeUtils.getInstance().getStringDate(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            interactionListBean.fComment = getComment();
            mDynamicDetailsCommentAdapter.addData(interactionListBean, 0);
        }
    }

    @Override
    public void starSuccess(boolean praise) {
        if (!praise) {
            if (mDynamicUserInfoAdapter != null) {
                mDynamicUserInfoAdapter.starPlus();
                ToastUtils.showSuccess(StringUtils.getInstance().getString(R.string.tip_star_success));
            }
        } else {
            ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_can_not_repeat_like));
        }
    }

    @Override
    public void collectionSuccess() {
        if (mDynamicUserInfoAdapter != null) {
            mDynamicUserInfoAdapter.collectionSuccess(true);
            ToastUtils.showSuccess(StringUtils.getInstance().getString(R.string.tip_favorite_success));
        }
    }

    @Override
    public void unLikeSuccess(boolean praise) {
        if (!praise) {
            if (mDynamicUserInfoAdapter != null) {
                mDynamicUserInfoAdapter.unlikePlus();
            }
        } else {
            ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_can_not_repeat_un_like));
        }
    }

    @Override
    public void initPreview(DynamicConfigBean successOb) {
        if (!TextUtils.isEmpty(successOb.status) && successOb.status.equals("0")) {
            clDynamicDetailsBottomComment.setVisibility(View.GONE);
            isShowComment = false;
        }
        getPresenter().getDynamicInfo(mDynamicId);
    }

    @Override
    public void startFavoriteActivity() {
        intent2Activity(FavoritesActivity.class);
    }

    @Override
    public void initData2View(VideoDetailsBean successOb) {
        if (successOb.contentInfo == null) {
            showLayoutStatus(3);
        } else {
            showLayoutStatus(1);
            initVideo(successOb.contentInfo.fTitle, ResourcesUtils.getInstance().getImagePath(successOb.contentInfo.fVideo));
        }
    }

    @Override
    public void initDynamicInfoData2View(DynamicInfoBean successOb) {
        if (successOb.dynamic == null) {
            showLayoutStatus(3);
        } else {
            showLayoutStatus(1);
            rcvDynamicDetails.setLayoutManager(new LinearLayoutManager(this));
            mConcatAdapter = new ConcatAdapter();
            rcvDynamicDetails.setAdapter(mConcatAdapter);
            /*
             * person info
             */
            mDynamicUserInfoAdapter = new DynamicUserInfoAdapter(this);
            mDynamicUserInfoAdapter.setOnItemClickListener((o, position, type) -> {
                if (type == 0) {
                    /*
                     * start add friend activity
                     */
                    getPresenter().addFriends(successOb.dynamic);
                } else if (type == 2) {
                    /*
                     * start chat activity
                     */
                    startChatActivity(successOb.dynamic);
                } else if (type == 3) {
                    /*
                     * like
                     */
                    getPresenter().dynamicFabulous(successOb.dynamic.fId);
                } else if (type == 4) {
                    /*
                     * Favorite
                     */
                    getPresenter().favorite(successOb.status, successOb.dynamic.fId);
                } else if (type == 5) {
                    getPresenter().dynamicDislike(successOb.dynamic.fId);

                }
            });
            mDynamicUserInfoAdapter.setPersonData(successOb);
            mConcatAdapter.addAdapter(mDynamicUserInfoAdapter);
            initDynamicInfoData2View(successOb.interactionList);
            initVideo(successOb.dynamic.fTitle, ResourcesUtils.getInstance().getImagePath(successOb.dynamic.fVideo));
        }
    }

    @Override
    public void startLoginActivity() {
        intent2Activity(LoginActivity.class);
    }

    @Override
    public String getComment() {
        return etDynamicDetailsBottomComment.getText().toString().trim();
    }

    @Override
    public void clearComment() {
        etDynamicDetailsBottomComment.setText("");
    }

}
